<template>
  <div class="task-edit-page">
    <div class="page-container">
      <div class="page-header">
        <h2 class="page-title">编辑任务</h2>
        <el-button @click="$router.back()">返回</el-button>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>

      <el-form
        v-else
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="120px"
        class="form-container"
      >
        <!-- 基本信息 -->
        <el-card class="form-section" header="基本信息">
          <el-form-item label="任务名称" prop="name">
            <el-input
              v-model="taskForm.name"
              placeholder="请输入任务名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="任务描述" prop="description">
            <el-input
              v-model="taskForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入任务描述"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="调度类型" prop="schedule_type">
            <el-radio-group v-model="taskForm.schedule_type">
              <el-radio label="manual" style="margin-right: 20px;">手动执行</el-radio>
              <el-radio label="scheduled" style="margin-right: 20px;">定时执行</el-radio>
              <el-radio label="triggered">触发执行</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            v-if="taskForm.schedule_type === 'scheduled'"
            label="定时配置"
            prop="schedule_config"
          >
            <el-input
              v-model="taskForm.schedule_config"
              placeholder="Cron表达式，如: 0 */6 * * * (每6小时执行一次)"
            />
            <div class="help-text">
              支持Cron表达式，格式: 分 时 日 月 周
            </div>
          </el-form-item>

          <el-form-item label="任务状态" prop="status">
            <el-switch
              v-model="taskForm.enabled"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-card>

        <!-- 源代码库 -->
        <el-card class="form-section" header="源代码库">
          <el-form-item label="源代码库" prop="source_repo_id">
            <el-select
              v-model="taskForm.source_repo_id"
              placeholder="请选择源代码库"
              style="width: 100%"
              @change="handleSourceRepoChange"
            >
              <el-option
                v-for="repo in sourceRepositories"
                :key="repo.id"
                :label="`${repo.name} (${repo.platform})`"
                :value="repo.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="源分支" prop="source_branch">
            <el-select
              v-model="taskForm.source_branch"
              placeholder="请选择源分支"
              style="width: 100%"
              :loading="branchesLoading"
              :disabled="!taskForm.source_repo_id"
            >
              <el-option
                v-for="branch in sourceBranches"
                :key="branch"
                :label="branch"
                :value="branch"
              />
            </el-select>
          </el-form-item>
        </el-card>

        <!-- 目标代码库 -->
        <el-card class="form-section" header="目标代码库">
          <el-form-item label="目标代码库">
            <div class="target-repos">
              <div
                v-for="(target, index) in taskForm.target_repos"
                :key="index"
                class="target-repo-item"
              >
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item :prop="`target_repos.${index}.repo_id`" :rules="targetRepoRules">
                      <el-select
                        v-model="target.repo_id"
                        placeholder="选择目标库"
                        style="width: 100%"
                        @change="(value) => handleTargetRepoChange(index, value)"
                      >
                        <el-option
                          v-for="repo in targetRepositories"
                          :key="repo.id"
                          :label="`${repo.name} (${repo.platform})`"
                          :value="repo.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item :prop="`target_repos.${index}.branch`" :rules="targetBranchRules">
                      <el-select
                        v-model="target.branch"
                        placeholder="选择目标分支"
                        style="width: 100%"
                        :loading="branchesLoading"
                        :disabled="!target.repo_id"
                      >
                        <el-option
                          v-for="branch in getTargetBranches(index)"
                          :key="branch"
                          :label="branch"
                          :value="branch"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item>
                      <el-input
                        v-model="target.branch_mapping"
                        placeholder="分支映射 (可选)"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-button
                      type="danger"
                      :icon="Delete"
                      circle
                      @click="removeTargetRepo(index)"
                      :disabled="taskForm.target_repos.length <= 1"
                    />
                  </el-col>
                </el-row>
              </div>
            </div>
            <el-button
              type="primary"
              :icon="Plus"
              @click="addTargetRepo"
              style="margin-top: 10px"
            >
              添加目标库
            </el-button>
          </el-form-item>
        </el-card>

        <!-- 验证配置 -->
        <el-card class="form-section" header="验证配置">
          <el-form-item label="启用验证">
            <el-switch
              v-model="taskForm.verification_enabled"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>

          <template v-if="taskForm.verification_enabled">
            <el-form-item label="验证方式">
              <el-checkbox-group v-model="taskForm.verification_methods">
                <el-checkbox label="commit_id">提交ID验证</el-checkbox>
                <el-checkbox label="file_content">文件内容验证</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item
              v-if="taskForm.verification_methods.includes('file_content')"
              label="验证文件"
            >
              <el-input
                v-model="taskForm.verification_files"
                type="textarea"
                :rows="3"
                placeholder="请输入需要验证的文件路径，每行一个，支持通配符"
              />
            </el-form-item>
          </template>
        </el-card>

        <!-- 通知配置 -->
        <el-card class="form-section" header="通知配置">
          <el-form-item label="启用通知">
            <el-switch
              v-model="taskForm.notification_enabled"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>

          <template v-if="taskForm.notification_enabled">
            <el-form-item label="通知邮箱">
              <el-input
                v-model="taskForm.notification_emails"
                placeholder="请输入通知邮箱，多个邮箱用逗号分隔"
              />
            </el-form-item>

            <el-form-item label="通知条件">
              <el-checkbox-group v-model="taskForm.notification_conditions">
                <el-checkbox label="success">成功时通知</el-checkbox>
                <el-checkbox label="failure">失败时通知</el-checkbox>
                <el-checkbox label="rollback">回滚时通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </template>
        </el-card>

        <!-- 表单操作 -->
        <div class="form-footer">
          <el-button @click="$router.back()">取消</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            保存修改
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { taskApi, repositoryApi } from '../api'

const router = useRouter()
const route = useRoute()

// 获取任务ID
const taskId = computed(() => parseInt(route.params.id))

// 表单引用
const taskFormRef = ref()
const loading = ref(false)
const submitting = ref(false)
const branchesLoading = ref(false)
const originalTaskData = ref(null)

// 源代码库和目标代码库数据
const sourceRepositories = ref([])
const targetRepositories = ref([])
const sourceBranches = ref([])
const targetBranchesMap = ref({})

// 任务表单数据
const taskForm = reactive({
  name: '',
  description: '',
  schedule_type: 'manual',
  schedule_config: '',
  enabled: true,
  source_repo_id: null,
  source_branch: '',
  target_repos: [
    {
      repo_id: null,
      branch: '',
      branch_mapping: ''
    }
  ],
  verification_enabled: false,
  verification_methods: [],
  verification_files: '',
  notification_enabled: false,
  notification_emails: '',
  notification_conditions: []
})

// 表单验证规则
const taskRules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 2, max: 100, message: '任务名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  schedule_type: [
    { required: true, message: '请选择调度类型', trigger: 'change' }
  ],
  schedule_config: [
    {
      validator: (rule, value, callback) => {
        if (taskForm.schedule_type === 'scheduled' && !value) {
          callback(new Error('定时配置不能为空'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  source_repo_id: [
    { required: true, message: '请选择源代码库', trigger: 'change' }
  ],
  source_branch: [
    { required: true, message: '请选择源分支', trigger: 'change' }
  ]
}

const targetRepoRules = [
  { required: true, message: '请选择目标库', trigger: 'change' }
]

const targetBranchRules = [
  { required: true, message: '请选择目标分支', trigger: 'change' }
]

// 获取任务详情
const fetchTaskDetail = async () => {
  if (!taskId.value) return

  loading.value = true
  try {
    const response = await taskApi.getTask(taskId.value)
    const taskData = response.data

    if (!taskData) {
      ElMessage.error('任务不存在')
      router.push('/tasks')
      return
    }

    originalTaskData.value = { ...taskData }

    // 填充表单数据
    Object.keys(taskForm).forEach(key => {
      if (key in taskData) {
        taskForm[key] = taskData[key]
      }
    })

    // 处理特殊字段
    taskForm.enabled = taskData.status === 'enabled'

    // 处理分支映射
    if (taskData.branch_mapping) {
      const branchMappings = []
      Object.entries(taskData.branch_mapping).forEach(([sourceBranch, targets]) => {
        Object.entries(targets).forEach(([repoId, targetBranch]) => {
          branchMappings.push({
            repo_id: parseInt(repoId),
            branch: targetBranch,
            branch_mapping: targetBranch !== sourceBranch ? targetBranch : ''
          })
        })
      })

      if (branchMappings.length > 0) {
        taskForm.source_branch = Object.keys(taskData.branch_mapping)[0] || ''
        taskForm.target_repos = branchMappings
      }
    }

    // 获取源代码库分支
    if (taskForm.source_repo_id) {
      fetchBranches(taskForm.source_repo_id, 'source')
    }

    // 获取目标代码库分支
    taskForm.target_repos.forEach((target, index) => {
      if (target.repo_id) {
        fetchBranches(target.repo_id, 'target')
      }
    })
  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
    router.push('/tasks')
  } finally {
    loading.value = false
  }
}

// 获取源代码库列表
const fetchSourceRepositories = async () => {
  try {
    const response = await repositoryApi.getRepositories({ type: 'source' })
    sourceRepositories.value = response.data?.items || []
  } catch (error) {
    console.error('获取源代码库失败:', error)
    ElMessage.error('获取源代码库失败')
  }
}

// 获取目标代码库列表
const fetchTargetRepositories = async () => {
  try {
    const response = await repositoryApi.getRepositories({ type: 'target' })
    targetRepositories.value = response.data?.items || []
  } catch (error) {
    console.error('获取目标代码库失败:', error)
    ElMessage.error('获取目标代码库失败')
  }
}

// 获取代码库分支
const fetchBranches = async (repoId, type = 'source') => {
  if (!repoId) return

  try {
    const response = await repositoryApi.getBranches(repoId)
    const branches = response.data?.branches || []

    if (type === 'source') {
      sourceBranches.value = branches
    } else {
      targetBranchesMap.value[repoId] = branches
    }
  } catch (error) {
    console.error('获取分支失败:', error)
    // ElMessage.error('获取分支失败') // 静默失败，避免阻塞用户操作
  }
}

// 处理源代码库变化
const handleSourceRepoChange = (repoId) => {
  taskForm.source_branch = ''
  if (repoId) {
    fetchBranches(repoId, 'source')
  }
}

// 处理目标代码库变化
const handleTargetRepoChange = (index, repoId) => {
  taskForm.target_repos[index].branch = ''
  if (repoId) {
    fetchBranches(repoId, 'target')
  }
}

// 获取目标代码库的分支列表
const getTargetBranches = (index) => {
  const repoId = taskForm.target_repos[index].repo_id
  return targetBranchesMap.value[repoId] || []
}

// 添加目标代码库
const addTargetRepo = () => {
  taskForm.target_repos.push({
    repo_id: null,
    branch: '',
    branch_mapping: ''
  })
}

// 移除目标代码库
const removeTargetRepo = (index) => {
  if (taskForm.target_repos.length > 1) {
    taskForm.target_repos.splice(index, 1)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await taskFormRef.value.validate()

    submitting.value = true

    // 构建提交数据
    const submitData = {
      ...taskForm,
      status: taskForm.enabled ? 'enabled' : 'disabled',
      branch_mapping: {}
    }

    // 构建分支映射
    submitData.branch_mapping[taskForm.source_branch] = {}
    taskForm.target_repos.forEach(target => {
      if (target.repo_id && target.branch) {
        const targetBranch = target.branch_mapping || target.branch
        submitData.branch_mapping[taskForm.source_branch][target.repo_id] = targetBranch
      }
    })

    // 移除前端专用字段
    delete submitData.enabled
    delete submitData.target_repos

    await taskApi.updateTask(taskId.value, submitData)
    ElMessage.success('任务更新成功')
    router.push('/tasks')
  } catch (error) {
    console.error('更新任务失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (originalTaskData.value) {
    // 恢复到原始数据
    Object.keys(taskForm).forEach(key => {
      if (key in originalTaskData.value) {
        taskForm[key] = originalTaskData.value[key]
      }
    })
    taskForm.enabled = originalTaskData.value.status === 'enabled'
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([
    fetchSourceRepositories(),
    fetchTargetRepositories()
  ])
  fetchTaskDetail()
})
</script>

<style scoped>
.task-edit-page {
  padding: 0;
}

.form-container {
  max-width: 1000px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 20px;
}

.target-repos {
  width: 100%;
}

.target-repo-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-footer {
  text-align: center;
  margin-top: 30px;
}

.loading-container {
  padding: 20px;
}
</style>
